<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册 - Demo系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .register-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            width: 100%;
            max-width: 450px;
            position: relative;
            overflow: hidden;
            margin: 20px 0;
        }

        .register-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .register-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .register-title {
            color: #333;
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .register-subtitle {
            color: #666;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
            background-color: #f8f9fa;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
            background-color: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-input.error {
            border-color: #dc3545;
        }

        .form-input.success {
            border-color: #28a745;
        }

        .error-message {
            color: #dc3545;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .success-message {
            color: #28a745;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }

        .password-strength {
            margin-top: 8px;
            display: none;
        }

        .strength-bar {
            width: 100%;
            height: 4px;
            background-color: #e1e5e9;
            border-radius: 2px;
            overflow: hidden;
        }

        .strength-fill {
            height: 100%;
            width: 0%;
            border-radius: 2px;
            transition: all 0.3s ease;
        }

        .strength-text {
            font-size: 12px;
            margin-top: 4px;
            color: #666;
        }

        .register-button {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
        }

        .register-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .register-button:active {
            transform: translateY(0);
        }

        .register-button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .register-footer {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e1e5e9;
        }

        .footer-text {
            color: #666;
            font-size: 14px;
        }

        .footer-link {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .footer-link:hover {
            color: #764ba2;
        }

        .loading {
            display: none;
            text-align: center;
            margin-top: 10px;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: none;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .field-check {
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-left: 8px;
            border-radius: 50%;
            font-size: 10px;
            text-align: center;
            line-height: 16px;
            color: white;
            font-weight: bold;
        }

        .field-check.checking {
            background-color: #ffc107;
        }

        .field-check.success {
            background-color: #28a745;
        }

        .field-check.error {
            background-color: #dc3545;
        }

        @media (max-width: 480px) {
            .register-container {
                padding: 30px 20px;
            }
            
            .register-title {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-header">
            <h1 class="register-title">创建账号</h1>
            <p class="register-subtitle">填写以下信息完成注册</p>
        </div>

        <div id="alert" class="alert"></div>

        <form id="registerForm">
            <div class="form-group">
                <label for="username" class="form-label">
                    用户名
                    <span id="usernameCheck" class="field-check" style="display: none;"></span>
                </label>
                <input type="text" id="username" name="username" class="form-input" required>
                <div class="error-message" id="usernameError"></div>
                <div class="success-message" id="usernameSuccess"></div>
            </div>

            <div class="form-group">
                <label for="password" class="form-label">密码</label>
                <input type="password" id="password" name="password" class="form-input" required>
                <div class="password-strength" id="passwordStrength">
                    <div class="strength-bar">
                        <div class="strength-fill" id="strengthFill"></div>
                    </div>
                    <div class="strength-text" id="strengthText">密码强度</div>
                </div>
                <div class="error-message" id="passwordError"></div>
            </div>

            <div class="form-group">
                <label for="confirmPassword" class="form-label">确认密码</label>
                <input type="password" id="confirmPassword" name="confirmPassword" class="form-input" required>
                <div class="error-message" id="confirmPasswordError"></div>
                <div class="success-message" id="confirmPasswordSuccess"></div>
            </div>

            <div class="form-group">
                <label for="email" class="form-label">
                    邮箱地址
                    <span id="emailCheck" class="field-check" style="display: none;"></span>
                </label>
                <input type="email" id="email" name="email" class="form-input" required>
                <div class="error-message" id="emailError"></div>
                <div class="success-message" id="emailSuccess"></div>
            </div>

            <div class="form-group">
                <label for="phone" class="form-label">
                    手机号码（可选）
                    <span id="phoneCheck" class="field-check" style="display: none;"></span>
                </label>
                <input type="tel" id="phone" name="phone" class="form-input">
                <div class="error-message" id="phoneError"></div>
                <div class="success-message" id="phoneSuccess"></div>
            </div>

            <button type="submit" class="register-button" id="registerBtn">
                注册
            </button>

            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
                <span style="margin-left: 10px; color: #666;">正在注册...</span>
            </div>
        </form>

        <div class="register-footer">
            <p class="footer-text">
                已有账号？
                <a href="login.html" class="footer-link">立即登录</a>
            </p>
        </div>
    </div>

    <script>
        // API基础URL
        const API_BASE_URL = 'http://localhost:8080/api';

        // DOM元素
        const registerForm = document.getElementById('registerForm');
        const registerBtn = document.getElementById('registerBtn');
        const loading = document.getElementById('loading');
        const alert = document.getElementById('alert');

        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        // 表单提交处理
        registerForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 清除之前的错误状态
            clearErrors();
            hideAlert();
            
            // 获取表单数据
            const formData = new FormData(registerForm);
            const registerData = {
                username: formData.get('username').trim(),
                password: formData.get('password').trim(),
                confirmPassword: formData.get('confirmPassword').trim(),
                email: formData.get('email').trim(),
                phone: formData.get('phone').trim() || null
            };
            
            // 客户端验证
            if (!await validateForm(registerData)) {
                return;
            }
            
            // 显示加载状态
            showLoading(true);
            
            try {
                // 发送注册请求
                const response = await fetch(`${API_BASE_URL}/user/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(registerData)
                });
                
                const result = await response.json();
                
                if (result.code === 0) {
                    // 注册成功
                    showAlert('注册成功！即将跳转到登录页面...', 'success');
                    
                    // 延迟跳转到登录页
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 2000);
                } else {
                    // 注册失败
                    showAlert(result.message || '注册失败', 'error');
                }
            } catch (error) {
                console.error('注册请求失败:', error);
                showAlert('网络错误，请稍后重试', 'error');
            } finally {
                showLoading(false);
            }
        });

        // 表单验证
        async function validateForm(data) {
            let isValid = true;
            
            // 用户名验证
            if (!data.username) {
                showFieldError('username', '请输入用户名');
                isValid = false;
            } else if (data.username.length < 3 || data.username.length > 20) {
                showFieldError('username', '用户名长度必须在3-20位之间');
                isValid = false;
            }
            
            // 密码验证
            if (!data.password) {
                showFieldError('password', '请输入密码');
                isValid = false;
            } else if (data.password.length < 6 || data.password.length > 20) {
                showFieldError('password', '密码长度必须在6-20位之间');
                isValid = false;
            }
            
            // 确认密码验证
            if (!data.confirmPassword) {
                showFieldError('confirmPassword', '请确认密码');
                isValid = false;
            } else if (data.password !== data.confirmPassword) {
                showFieldError('confirmPassword', '两次输入的密码不一致');
                isValid = false;
            }
            
            // 邮箱验证
            if (!data.email) {
                showFieldError('email', '请输入邮箱地址');
                isValid = false;
            } else if (!isValidEmail(data.email)) {
                showFieldError('email', '请输入正确的邮箱格式');
                isValid = false;
            }
            
            // 手机号验证（可选）
            if (data.phone && !isValidPhone(data.phone)) {
                showFieldError('phone', '请输入正确的手机号格式');
                isValid = false;
            }
            
            return isValid;
        }

        // 邮箱格式验证
        function isValidEmail(email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }

        // 手机号格式验证
        function isValidPhone(phone) {
            const phoneRegex = /^1[3-9]\d{9}$/;
            return phoneRegex.test(phone);
        }

        // 密码强度检测
        function checkPasswordStrength(password) {
            const strengthIndicator = document.getElementById('passwordStrength');
            const strengthFill = document.getElementById('strengthFill');
            const strengthText = document.getElementById('strengthText');
            
            if (!password) {
                strengthIndicator.style.display = 'none';
                return;
            }
            
            strengthIndicator.style.display = 'block';
            
            let score = 0;
            let strength = '';
            let color = '';
            
            // 长度检查
            if (password.length >= 6) score++;
            if (password.length >= 8) score++;
            
            // 包含数字
            if (/\d/.test(password)) score++;
            
            // 包含小写字母
            if (/[a-z]/.test(password)) score++;
            
            // 包含大写字母
            if (/[A-Z]/.test(password)) score++;
            
            // 包含特殊字符
            if (/[^A-Za-z0-9]/.test(password)) score++;
            
            // 根据分数确定强度
            if (score <= 2) {
                strength = '弱';
                color = '#dc3545';
            } else if (score <= 4) {
                strength = '中等';
                color = '#ffc107';
            } else {
                strength = '强';
                color = '#28a745';
            }
            
            strengthFill.style.width = `${(score / 6) * 100}%`;
            strengthFill.style.backgroundColor = color;
            strengthText.textContent = `密码强度：${strength}`;
            strengthText.style.color = color;
        }

        // 检查字段唯一性
        async function checkFieldUniqueness(field, value) {
            if (!value) return;
            
            const checkElement = document.getElementById(field + 'Check');
            const input = document.getElementById(field);
            
            // 显示检查状态
            checkElement.style.display = 'inline-block';
            checkElement.className = 'field-check checking';
            checkElement.textContent = '?';
            
            try {
                const response = await fetch(`${API_BASE_URL}/user/check-${field}?${field}=${encodeURIComponent(value)}`);
                const result = await response.json();
                
                if (result.code === 0) {
                    if (result.data) {
                        // 字段已存在
                        showFieldError(field, `该${getFieldDisplayName(field)}已被使用`);
                        checkElement.className = 'field-check error';
                        checkElement.textContent = '✕';
                    } else {
                        // 字段可用
                        showFieldSuccess(field, `该${getFieldDisplayName(field)}可以使用`);
                        checkElement.className = 'field-check success';
                        checkElement.textContent = '✓';
                    }
                }
            } catch (error) {
                console.error(`检查${field}失败:`, error);
                checkElement.style.display = 'none';
            }
        }

        // 获取字段显示名称
        function getFieldDisplayName(field) {
            const displayNames = {
                username: '用户名',
                email: '邮箱',
                phone: '手机号'
            };
            return displayNames[field] || field;
        }

        // 显示字段错误
        function showFieldError(field, message) {
            const input = document.getElementById(field);
            const error = document.getElementById(field + 'Error');
            const success = document.getElementById(field + 'Success');
            
            input.classList.add('error');
            input.classList.remove('success');
            error.textContent = message;
            error.style.display = 'block';
            if (success) success.style.display = 'none';
        }

        // 显示字段成功
        function showFieldSuccess(field, message) {
            const input = document.getElementById(field);
            const error = document.getElementById(field + 'Error');
            const success = document.getElementById(field + 'Success');
            
            input.classList.remove('error');
            input.classList.add('success');
            error.style.display = 'none';
            if (success) {
                success.textContent = message;
                success.style.display = 'block';
            }
        }

        // 清除错误状态
        function clearErrors() {
            const inputs = document.querySelectorAll('.form-input');
            const errors = document.querySelectorAll('.error-message');
            const successes = document.querySelectorAll('.success-message');
            
            inputs.forEach(input => {
                input.classList.remove('error', 'success');
            });
            errors.forEach(error => error.style.display = 'none');
            successes.forEach(success => success.style.display = 'none');
        }

        // 显示/隐藏加载状态
        function showLoading(show) {
            if (show) {
                registerBtn.style.display = 'none';
                loading.style.display = 'block';
            } else {
                registerBtn.style.display = 'block';
                loading.style.display = 'none';
            }
        }

        // 显示提示信息
        function showAlert(message, type) {
            alert.textContent = message;
            alert.className = `alert alert-${type}`;
            alert.style.display = 'block';
        }

        // 隐藏提示信息
        function hideAlert() {
            alert.style.display = 'none';
        }

        // 防抖检查函数
        const debouncedCheckUsername = debounce((value) => checkFieldUniqueness('username', value), 500);
        const debouncedCheckEmail = debounce((value) => checkFieldUniqueness('email', value), 500);
        const debouncedCheckPhone = debounce((value) => checkFieldUniqueness('phone', value), 500);

        // 输入框事件监听
        document.getElementById('username').addEventListener('input', function() {
            const value = this.value.trim();
            if (value.length >= 3) {
                debouncedCheckUsername(value);
            } else {
                document.getElementById('usernameCheck').style.display = 'none';
            }
        });

        document.getElementById('email').addEventListener('input', function() {
            const value = this.value.trim();
            if (isValidEmail(value)) {
                debouncedCheckEmail(value);
            } else {
                document.getElementById('emailCheck').style.display = 'none';
            }
        });

        document.getElementById('phone').addEventListener('input', function() {
            const value = this.value.trim();
            if (value && isValidPhone(value)) {
                debouncedCheckPhone(value);
            } else {
                document.getElementById('phoneCheck').style.display = 'none';
            }
        });

        document.getElementById('password').addEventListener('input', function() {
            checkPasswordStrength(this.value);
        });

        document.getElementById('confirmPassword').addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirmPassword = this.value;
            
            if (confirmPassword) {
                if (password === confirmPassword) {
                    showFieldSuccess('confirmPassword', '密码匹配');
                } else {
                    showFieldError('confirmPassword', '两次输入的密码不一致');
                }
            }
        });

        // 输入框焦点事件 - 清除错误状态
        document.querySelectorAll('.form-input').forEach(input => {
            input.addEventListener('focus', function() {
                this.classList.remove('error');
                const errorElement = document.getElementById(this.id + 'Error');
                if (errorElement) {
                    errorElement.style.display = 'none';
                }
            });
        });

        // 页面加载时检查是否已登录
        window.addEventListener('load', function() {
            const user = localStorage.getItem('user');
            if (user) {
                // 已登录，直接跳转到主页
                window.location.href = 'index.html';
            }
        });
    </script>
</body>
</html>
